package com.xtaller.easy.admin.tps;

import com.alibaba.fastjson.JSONObject;
import com.xtaller.common.bean.JWTResult;
import com.xtaller.common.kit.JwtKit;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by Taller on 2018/5/15
 */
public class NetKit {
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");

        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknow".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();

            if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
                //根据网卡获取本机配置的IP地址
                InetAddress inetAddress = null;
                try {
                    inetAddress = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inetAddress.getHostAddress();
            }
        }

        //对于通过多个代理的情况，第一个IP为客户端真实的IP地址，多个IP按照','分割
        if(null != ipAddress && ipAddress.length() > 15){
            //"***.***.***.***".length() = 15
            if(ipAddress.indexOf(",") > 0){
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

    public static JSONObject getClientInfo(HttpServletRequest request){
        JSONObject object = new JSONObject();
        String token = request.getHeader("token");
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String ip = NetKit.getIpAddr(request);
        String creator = "0";
        try {
            JWTResult jwt = JwtKit.validateJWT(token);
            creator = jwt.getClaims().getId();
        }catch (Exception ex){}

        object.put("ip", ip);
        object.put("id", creator);
        object.put("token", token);
        object.put("url", url);
        object.put("method", method);
        object.put("error", 0);
        object.put("type", 2);
        object.put("creator", creator);
        object.put("userId", creator);
        return object;
    }
}
